#!/media/DISK_A1/system/usr/bin/lua

require('keevi');

installed_txt = "\n"..os.capture('/media/DISK_A1/system/bin/opkg list-installed 2>&1', true);
available_txt = "\n"..os.capture('/media/DISK_A1/system/bin/opkg list 2>&1', true).."e";
upgradable_txt = "\n"..os.capture('/media/DISK_A1/system/bin/opkg list-upgradable 2>&1', true);

packages = {};
i = 1;
while true do
	s, e, package, version, description = string.find(available_txt, "\n([_a-z0-9%.%+%-]+) %- ([a-zA-Z0-9%.%+%-]+) %- (.-)\n%w", i-1);
	if s == nil then break end;
	packages[package] = {version=version, description=description};
--	echo(package.." - "..version.." = "..description.."\n");
--	echo(s.." - "..e.."\n");
	i = e-1;
end

--for package, version in string.gmatch(available_txt, "\n([_a-z0-9%.%+%-]+) %- ([a-zA-Z0-9%.%+%-]+) %- ") do
--  packages[package] = {version=version};
--  print(package.." - "..version.." = ");
--end

for package, version in string.gmatch(installed_txt, "\n([_a-z0-9%.%+%-]+) %- ([a-zA-Z0-9%.%+%-]+)") do
  if packages[package] == nil then packages[package] = {} end
  packages[package].installed_version = version;
--  print(package.." - "..version);
end

for package, version1, version2 in string.gmatch(upgradable_txt, "\n([_a-z0-9%.%+%-]+) %- ([a-zA-Z0-9%.%+%-]+) %- ([a-zA-Z0-9%.%+%-]+)") do
  packages[package].upgradable = 1;
  packages[package].version = version2;
--  print(package.." - "..version);
end

--_HEADERS["Content-type"] = "application/json";
callback = _GET.callback or 'callback';
echo(callback.."("..json.encode(packages)..");");

